'use client'

import Link from 'next/link'
import { usePathname } from 'next/navigation'
import { useEffect, useState } from 'react'
import { Clapperboard,Menu } from 'lucide-react'
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet"
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Button } from "@/components/ui/button"
import { useRouter } from 'next/navigation'

const navigation = [
  { href: '/', label: '首页' },
  { href: '/topics', label: '项目' },
  { href: '/notion', label: '文案' },
  { href: '/progress', label: '进度' },
  { href: '/music', label: '音乐' },
  { href: '/read', label: '提词' },
  { href: '/cover', label: '封面' },
]

export default function Header() {
  const pathname = usePathname()
  const router = useRouter()
  const [user, setUser] = useState<{ email?: string } | null>(null)

  const handleLogout = () => {
    localStorage.clear()
    setUser(null)
    router.push('/')
  }

  useEffect(() => {
    const fetchUser = async () => {
        try {
            const token = localStorage.getItem('token');
            const response = await fetch('/api/auth/me', {
                headers: {
                    'Authorization': `Bearer ${token}`
                }
            });
            if (response.ok) {
                const userData = await response.json();
                setUser(userData);
            } else {
                console.error('Failed to fetch user data');
            }
        } catch (error) {
            console.error('Error fetching user:', error);
        }
    };

    fetchUser();
}, []);

return (
  <header className="bg-white/80 backdrop-blur-md sticky top-0 z-50">
    <nav className="mx-auto container px-4 lg:px-8" aria-label="Top">
      <div className="flex w-full items-center justify-between border-b border-gray-200/50 py-4 md:py-6">
        <div className="flex items-center">
          <Link href="/" className="flex items-center space-x-2">
            <span className="sr-only">VideoFlow</span>
            <Clapperboard className='w-6 h-6 text-indigo-900'/>
            <span className="text-xl font-bold text-gray-900">VideoFlow</span>
          </Link>
          
          {/* 桌面导航 */}
          <div className="hidden md:flex items-center ml-6 space-x-4">
            {navigation.map((link) => (
              <Link
                key={link.href}
                href={link.href}
                className={`text-sm font-medium px-3 py-2 rounded-lg transition-colors duration-200
                  ${pathname === link.href
                    ? 'text-gray-900 bg-gray-100/50'
                    : 'text-gray-700 hover:text-gray-900 hover:bg-gray-100/50'
                  }`}
              >
                {link.label}
              </Link>
            ))}
          </div>
        </div>

        <div className="flex items-center gap-4">
          {/* 移动端菜单 */}
          <Sheet>
            <SheetTrigger asChild className="md:hidden">
              <Button variant="ghost" size="icon">
                <Menu className="h-5 w-5" />
              </Button>
            </SheetTrigger>
            <SheetContent side="left" className="w-[240px] sm:w-[280px]">
              <div className="flex flex-col gap-4 py-4">
                {navigation.map((link) => (
                  <Link
                    key={link.href}
                    href={link.href}
                    className={`text-sm font-medium px-3 py-2 rounded-lg transition-colors duration-200
                      ${pathname === link.href
                        ? 'text-gray-900 bg-gray-100/50'
                        : 'text-gray-700 hover:text-gray-900 hover:bg-gray-100/50'
                      }`}
                  >
                    {link.label}
                  </Link>
                ))}
              </div>
            </SheetContent>
          </Sheet>

          {/* 用户菜单 */}
          {user ? (
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="ghost" className="flex items-center gap-2">
                  <span className="hidden sm:inline">{user.email}</span>
                  <span className="sm:hidden">{user.email}</span>
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent className="w-48">
                <DropdownMenuLabel>账户</DropdownMenuLabel>
                <DropdownMenuSeparator />
                <DropdownMenuItem onClick={handleLogout}>
                  退出登录
                </DropdownMenuItem>
              </DropdownMenuContent>
            </DropdownMenu>
          ) : (
            <>
              <Button variant="outline" onClick={() => router.push('/login')} className="hidden sm:flex">
                登录
              </Button>
              <Button onClick={() => router.push('/register')} className="hidden sm:flex">
                注册
              </Button>
              <Button variant="ghost" onClick={() => router.push('/login')} className="sm:hidden">
                登录
              </Button>
            </>
          )}
        </div>
      </div>
    </nav>
  </header>
)
}